// pages/goods/index/index.js
var app = getApp();
var core = app.requirejs('core');
var $ = app.requirejs('jquery');
var diyad = app.requirejs('biz/ad');
const api = require("../../../utils/api.js")
Page(app.sr.page({

  /**
   * 页面的初始数据
   */
  data: {
    loadKey: true,
    allnavlist: false,
    classLevel: 3,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideTabBar({
      // animation: true,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this
    //初始化数据
    this.setData({
      loaded: false, //下拉刷新用的
    })
    _this.initFunction()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let _this = this
    if (this.data.loaded == true) {
      return
    }
    _this.getList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  initFunction: function () {
    app.miniprogram(function (res) { }) //小程序配置
    var $this = this;
    wx.getSetting({ //获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限。
      success: function (res) {
        var limits = res.authSetting['scope.userInfo'];
        $this.setData({
          limits: limits
        })
      }
    })
    // 加载分类的id  用于分类跳转
    let cateid = app.getCache("cateid")
    if (cateid) {
      $this.setData({
        params: {
          categoryId: cateid,
        },
        currentTab: cateid
      })
      this.goodsClassOne(cateid);
      // this.goodsClasstotal()
    } else {
      $this.setData({
        params: {
          categoryId: 1,
        },
        currentTab: '1'
      })
      // this.goodsClasstotal()
      this.goodsClassOne(cateid);
    }

    /**启动广告 */
    diyad.get(this, function (res) { })

    //初始化商品列表
    $this.setData({
      current: 1,
      list: []
    })
    $this.getList(); //有商品查询
    // app.setCache("cateid", null)
  },
  //查询总分类
  goodsClasstotal() {
    var $this = this;
    let apicontent = api.goods.goodsClasstotal()
    core.get(apicontent, {}, function (result) {
      let category_total = result.data.rows
      let classLevel = result.data.classLevel
      let category_three = []

      // 暂时设置等级
      classLevel = $this.data.classLevel
      if (classLevel == 3) {
        category_total[1].listTwo[0].select = "checked"
        category_total[1].openshow = true
        category_three = category_total[1].listTwo[0].listThree
      } else {
        category_total[1].select = "checked"
        category_three = category_total[1].listTwo
      }
      $this.setData({
        category_total,
        category_three,
        // classLevel:result.data.classLevel
      })
    })
  },
  //搜索一级分类
  goodsClassOne: function (cateid) {
    var $this = this;
    let apicontent = api.goods.goodsClass()
    if (!cateid) {
      $this.setData({
        current2name: 'cate1'
      })
    }
    // 查询分类
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    core.get(apicontent, {}, function (result) {
      if (cateid) {
        if (result) {
          result.map((v, i) => {
            if (v.id == cateid) {
              $this.setData({
                current2name: 'cate' + v.id
              })
            }
          })
        }
      }
      $this.setData({
        category_parent: result,
        show: true,
        parentId: result[1].parentId
      });
      wx.hideLoading({
        complete: (res) => { },
      })
      // $this.goodsClasstwo()
    });

  },
  //获取商品列表
  getList: function () {
    var $this = this;
    let apicontent = api.goods.goodsListByCate()
    if ($this.data.loadKey) {
      $this.setData({
        loadKey: false
      })
      $this.data.params.current = $this.data.current;
      // var keywords = $this.data.navname
      core.get(apicontent, {
        current: $this.data.params.current,
        categoryId: $this.data.params.categoryId ? $this.data.params.categoryId : "1"
      }, function (result) {
        var data = {
          loading: false,
          count: result.data.total,
          show: true,
          loadKey: true
        };

        if (result.data.rows.length == 0) {
          result.data.rows = [];
        }
        if (result.data.rows.length > 0) {
          result.data.rows.forEach(Element => {
            app.sr.track('expose_sku_component', {
              "sku": {
                "sku_id": String(Element.id),
                "sku_name": Element.title
              },
              "spu": {
                "spu_id": String(Element.id),
                "spu_name": Element.title
              },
            })
          })
          if (result.data.rows.option) {
            // result.data.rows.option.banner = JSON.stringify(result.data.rows.option.banner)
          }
          data.current = $this.data.current + 1;
          data.list = $this.data.list.concat(result.data.rows);
          if (result.data.rows.length < result.data.size) {
            data.loaded = true
          }
          result.data.rows.forEach(e => {
            e.imgBase = ""
          })
        }

        $this.setData(data);
      });
    }
  },
  //选择标签
  tabNav: function (e) {
    var params = this.data.params;
    let category_parent = this.data.category_parent
    let index = e.currentTarget.dataset.index
    params.categoryId = category_parent[index].id
    params.current = 1;
    this.setData({
      params: params,
      list: [],
      current: 1,
      loading: true,
      loaded: false,
      currentTab: params.categoryId
    });
    app.setCache("cateid", params.categoryId)
    let _this = this
    _this.getList();
    /**启动广告 */
    diyad.get(this, function (res) {


    })
  },
  //选择二级分类
  changenavitem(e) {
    let index = e.currentTarget.dataset.index
    let idx = e.currentTarget.dataset.idx
    let category_total = this.data.category_total
    let categroytwo = category_total[index].listTwo
    let category_three = this.data.category_three
    categroytwo.forEach(ele => {
      ele.select = ''
    })
    categroytwo[idx].select = "checked"
    if (categroytwo[idx].listThree) {
      category_three = categroytwo[idx].listThree
    }
    category_total[index].listTwo = categroytwo
    app.matomo.trackEvent("点击", "二级分类", categroytwo[idx].name)
    this.setData({
      category_three,
      category_total
    })
  },
  //选择一级菜单
  changenavlist(e) {
    let index = e.currentTarget.dataset.index
    let category_total = this.data.category_total
    // let classLevel = this.data.category_total.classLevel
    let classLevel = this.data.classLevel
    let categroyone = this.data.category_total[index]
    let categroytwo = []
    let category_three = []
    app.matomo.trackEvent("点击", "一级分类", categroyone.name)
    if (classLevel == 3) {
      categroytwo = categroyone.listTwo
      for (let i in categroyone) {
        category_total.forEach(ele => {
          ele.openshow = false
        })
        categroytwo.forEach(ele => {
          ele.select = ''
        })
        if (categroytwo.length > 0) {
          categroytwo[0].select = 'checked'
          if (categroytwo[0].listThree) {
            category_three = categroytwo[0].listThree
          }
        } else {
          category_three = []
        }
        categroyone.openshow = true
        category_total[index] = categroyone
      }

    } else {
      category_total.forEach(ele => {
        ele.select = ''
      })
      category_three = categroyone.listTwo
      category_total[index].select = 'checked'
    }
    this.setData({
      category_total,
      category_three,
    })
  },
  //跳到分类商品
  jumpcategory(e) {

    let id = e.currentTarget.dataset.id
    let parentid = e.currentTarget.dataset.parentid
    let title = e.currentTarget.dataset.title
    app.matomo.trackEvent("点击", "跳转分类", title)
    wx.navigateTo({
      url: '/pages/goods/goodlist/index?id=' + id + '&title=' + title,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  }
}))